package it.sisisoftware.jogmobile;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

public class AES {

	private static final String ALGORITHM = "AES/CBC/PKCS7Padding";// "AES";
    private static final String ALGORITHM2 = "AES/CBC/PKCS7Padding";// "AES";
    private static final String chiaveSegreta = "3vYr823Thfh92ei2pq5kf9sl41ksi3m2";
    private static final String iv = "9keislkdfmkq4r6v";
    private static final byte[] keyValue = chiaveSegreta.getBytes();
    private static final byte[] bIV = iv.getBytes();
    //private static final byte[] keyValue = 
        //new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };    
    

     public static String encrypt(String valueToEnc) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(bIV) );
        byte[] encValue = c.doFinal(valueToEnc.getBytes());
        
        String encryptedValue = Base64.encodeToString(encValue, 0);
        return encryptedValue;
    }

    public static String decrypt(String encryptedValue) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = Base64.decode(encryptedValue, 0);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, ALGORITHM2);
        // SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        // key = keyFactory.generateSecret(new DESKeySpec(keyValue));
        return key;
    }
}